package com.feng.oss.service.impl;

import com.aliyun.oss.OSS;

import com.aliyun.oss.OSSClientBuilder;
import com.feng.commonutils.R;
import com.feng.oss.service.OssService;
import com.feng.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public R uploadFileAvatar(MultipartFile file) {
        String endpoint= ConstantPropertiesUtils.END_POINT;
        String accessKeyId=ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret=ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName=ConstantPropertiesUtils.BUCKET_NAME;
        OSS ossClient=null;
        try{
            //创建OSS实例
             ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //获取上传文件流
            InputStream inputStream=file.getInputStream();
            //调用oss方法实现上传
            //获取文件名称
            String originalFilename = file.getOriginalFilename();
            //在文件名称添加随机唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //最新文件名称
            String newFileName=uuid+originalFilename;
            //将文件按照日期分类
            //2023/1/10/asdasdas01.jpg
            //获取当前日期
            String dataPath = new DateTime().toString("yyyy/MM/dd");
            //拼接
            newFileName=dataPath+"/"+newFileName;
            ossClient.putObject(bucketName,newFileName,inputStream);
            //把文件上传路径返回手动拼接回来
            //  https://edu-202323.oss-cn-guangzhou.aliyuncs.com/0E496F4649E354C0B12993C03903620B.png
            String url="https://"+bucketName+"."+endpoint+"/"+newFileName;
            return R.ok().data("url",url);

        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
        finally {
            //关闭
            ossClient.shutdown();
        }

    }
}
